package com.oss.base.dao;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.util.Assert;

/**
* Title: DaoUtil
* Description: dao层工具类
* Company: sungoin 
* @author   wjt
* @date       2016-1-25
*/
public class DaoUtil { 

    protected static final Logger log = Logger.getLogger(DaoUtil.class.getName());

    /**
    * Title: getHQL4Count
    * Description: 为计算纪录数量拼装HQL，判定是否含有"distinct"
    * @author   wjt
    * @date       2016-1-25
    * @param hql
    * @return
    */
    public static String getHQL4Count(String hql)
    {
        int formPos = hql.toLowerCase().indexOf("from ");
		Assert.isTrue(formPos != -1, " hql : " + hql + " must has a keyword 'from'");
		
        int distPos = hql.toLowerCase().indexOf(" distinct");
        if (distPos < 0)
            return hql = " select count (*) " + removeSelect(removeOrders(hql));

        //含有"distinct"  
        hql = " select count(" + hql.substring(distPos, formPos).trim() + ") " + removeSelect(removeOrders(hql));
        return hql;

    }
    
	/**
	* Title: removeSelect
	* Description: 去除hql的select 子句，未考虑union的情况.
	* @author   wjt
	* @date       2016-1-25
	* @param hql
	* @return
	*/
	public static String removeSelect(String hql) {
		Assert.hasText(hql);
		int beginPos = hql.toLowerCase().indexOf("from");
		Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'");
		return hql.substring(beginPos);
	} 

	/**
	* Title: removeOrders
	* Description: 去除hql的orderby 子句
	* @author   wjt
	* @date       2016-1-25
	* @param hql
	* @return
	*/
	public static String removeOrders(String hql) {
		Assert.hasText(hql);
		Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(hql);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, "");
		}
		m.appendTail(sb);
		return sb.toString();
	}

    /**
    * Title: append
    * Description: 拼装查询条件字符串
    * @author   wjt
    * @date       2016-1-25
    * @param hql
    * @param criteria
    * @return
    */
    public static String append(StringBuffer hql,String criteria){
	    if(hql == null) hql = new StringBuffer();
	    if(!"".equals(hql.toString())&&!"".equals(hql.toString().trim())){
		    return hql.append(" WHERE ").append(criteria).toString();
	    }	   
	    return hql.append(" AND ").append(criteria).toString();
    } 
	
    /**
    * Title: getWhereOrAnd
    * Description: 拼装查询条件字符串
    * @author   wjt
    * @date       2016-1-25
    * @param hql
    * @return
    */
    public static String getWhereOrAnd(String hql){
        if (hql == null || "".equals(hql))
            return " WHERE ";
        return " AND ";
    }
	
	/**
	* Title: getHqlFromVOProperty
	* Description: 根据对象的属性值拼装ＨＱＬ语句
	* @author   wjt
	* @date       2016-1-25
	* @param findObject
	* @return
	*/
	public static String getHqlFromVOProperty(Object findObject) {
		StringBuffer sql = new StringBuffer();
		sql.append(" From " + findObject.getClass().getName());

		PropertyDescriptor[] pd = PropertyUtils.getPropertyDescriptors(findObject.getClass());

		StringBuffer whereString = new StringBuffer();
		for (int i = 0; i < pd.length; i++) {
			PropertyDescriptor p = pd[i];

			if (p.getWriteMethod() == null || p.getReadMethod() == null) 
				continue;
			
			try {
				if (BeanUtils.getProperty(findObject, p.getName()) == null) 
					continue;
				
				if (BeanUtils.getProperty(findObject, p.getName()).equals("0") || BeanUtils.getProperty(findObject, p.getName()).equals("0.0")) 
					continue;
				
			} catch (Exception e) {
				continue;
			}

			if (whereString.length() == 0) {
				whereString.append(" WHERE ");
			} else {
				whereString.append(" AND ");
			}

			whereString.append(p.getName() + " = " + ":" + p.getName());
		}

		sql.append(whereString.toString());

		return sql.toString();
	}
	
	
	/****
	 * INSERT INTO table(field1,field2) VALUES('value1','value2');
	 * @param obj 传入要生成的实体，需与数据库表的字段一致
	 * @return 拼成的insert 语句
	*/
	public static String getSqlInset(Object obj) {
		try {
			Class<? extends Object> c = obj.getClass();
		
			//获取所有的字段
			Field[] fields = c.getDeclaredFields();
			//获取实体的类名，需与表名一致
			String tableName = c.getSimpleName();
			//生成INSERT INTO table(field1,field2) 部分
			StringBuffer sbField = new StringBuffer();
			//生成VALUES('value1','value2') 部分
			StringBuffer sbValue = new StringBuffer();
			sbField.append("INSERT INTO"+ tableName.toLowerCase() +"(");
			int fieldLength = fields.length;
			
			for(int i=0;i<fieldLength;i++){
		
				fields[i].setAccessible(true);
				sbField.append(fields[i].getName().toLowerCase()+',');
				sbValue.append("'"+fields[i].get(obj).toString() +"',");
		
			}
		
			return sbField.replace(sbField.length()-1, sbField.length(),") VALUES(").append(sbValue.replace(sbValue.length()-1, sbValue.length(),");")).toString();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
	
		return null;
	}



	public static String getSqlUpdate(Object obj) {


	try {



	Field[] fields = obj.getClass().getDeclaredFields();



	String tableName = obj.getClass().getSimpleName();



	StringBuffer sb = new StringBuffer();



	sb.append("UPDATE"+ tableName.toLowerCase() +"SET");



	int fieldLength = fields.length;



	for(int i=0;i<fieldLength;i++){




	fields[i].setAccessible(true);




	sb.append(fields[i].getName() +"= '"+ fields[i].get(obj) +"',");
	}
	return sb.replace(sb.length()-1, sb.length(),"").toString();


	} catch (IllegalAccessException e1) {



	e1.printStackTrace();


	}


	return null;

	}
}
